import { DrawerProps } from '@/components/base/base-drawer/BaseDrawer.vue'
import { reactive } from 'vue'
import { commonDeleteByIds } from '@/api/common/common'
import { useTable } from '@/hooks/base/TableHooks'
import { UpdateData } from '@/components/base/table/BaseTable.vue'

export interface DrawerHook {
  // 获取抽屉属性
  props: DrawerProps
  // 打开抽屉
  open: (title?: string) => void
  // 关闭抽屉
  close: () => void
  // 刷新数据
  refresh: () => void
  /**
   * 操作改变
   * @param data
   */
  handlerOperation: (data: UpdateData) => void
}
/**
 * 抽屉hooks
 * @param refName 表格refs名称
 * @param prop 抽屉属性
 */
export const useDrawer = (api?: string, title?: string, refName = 'baseDrawer'): DrawerHook => {
  const table = useTable()
  const metaTitle = title
  let drawerProps: DrawerProps = reactive({
    id: '',
    type: 1,
    placement: 'right',
    title: '默认标题',
    visible: false,
    api: api,
  })
  return {
    props: drawerProps,
    open: () => {
      drawerProps.visible = true
    },
    close: () => {
      drawerProps.visible = false
    },
    refresh: () => {
      drawerProps.visible = false
      table.requestPage()
    },
    async handlerOperation({ type, data }) {
      // 删除直接处理
      if (type === 3 && drawerProps.api) {
        if (window.confirm('你确认要删除选中的记录吗?')) {
          await commonDeleteByIds(drawerProps.api, data.id)
          table.requestPage()
        }
        return
      }
      const title = ['新增', '查看', '修改']
      drawerProps.id = data?.id ? data?.id : ''
      drawerProps.type = type
      drawerProps.visible = true
      drawerProps.title = title[type] + metaTitle
    },
  }
}
